<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="Content-Security-Policy" content="default-src * gap://ready file:; connect-src *; img-src * data: blob:; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline'">
    <title>图片编辑</title>
    <script src="./js/hybrid_html_uni.webview.1.5.5.js"></script>
	<style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #f0f0f0;
            touch-action: none;
        }
        .container {
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }
        #canvas {
            max-width: 100%;
            max-height: 100%;
            touch-action: none;
        }
        .toolbar {
            position: fixed;
            bottom: 20px;
            left: 10px;
            right: 10px;
            display: flex;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 10px 15px;
            border-radius: 30px;
            z-index: 100;
            overflow-x: auto;
            overflow-y: hidden;
            white-space: nowrap;
            scrollbar-width: none; /* Firefox */
            -ms-overflow-style: none; /* IE 10+ */
            max-width: calc(100vw - 20px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
		.toolbar::-webkit-scrollbar {
		    display: none; /* Chrome Safari */
		}
        .toolbar button {
            margin: 0 8px;
            padding: 10px 18px;
            border: none;
            border-radius: 20px;
            background-color: #4a90e2;
            color: white;
            font-size: 14px;
            cursor: pointer;
            outline: none;
            flex-shrink: 0;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            transition: all 0.2s ease;
        }
        .toolbar button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        .toolbar button.clear {
            background-color: #9b59b6;
        }
        .toolbar button.delete {
            background-color: #e74c3c;
        }
        .toolbar button.confirm {
            background-color: #2ecc71;
        }
        .toolbar button.undo {
            background-color: #f39c12;
        }
		.toolbar button.save {
		    background-color: #2ecc71;
		}
		.toolbar button.save:hover {
		    background-color: #27ae60;
		}
		.toolbar button.clear:hover {
		    background-color: #8e44ad;
		}
		
		.toolbar button.delete:hover {
		    background-color: #c0392b;
		}
		
		.toolbar button.confirm:hover {
		    background-color: #27ae60;
		}
		
		.toolbar button.undo:hover {
		    background-color: #d35400;
		}
        .shape-selector {
            position: fixed;
            bottom: 80px;
            left: 10px;
            right: 10px;
            display: flex;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 10px 15px;
            border-radius: 30px;
            z-index: 100;
            overflow-x: auto;
            overflow-y: hidden;
            white-space: nowrap;
            scrollbar-width: none;
            -ms-overflow-style: none;
            max-width: calc(100vw - 20px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
		.shape-selector::-webkit-scrollbar {
		    display: none;
		}
        .shape-btn {
            margin: 0 10px;
            padding: 8px 16px;
            border: none;
            border-radius: 20px;
            background-color: #5d6d7e;
            color: white;
            font-size: 14px;
            cursor: pointer;
            outline: none;
        }
        .shape-btn:hover {
            background-color: #4d5d6e;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        .text-input-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            z-index: 1000;
            display: none;
        }
        .text-input-container input {
            padding: 8px;
            margin-right: 10px;
            width: 200px;
        }
        .text-input-container button {
            padding: 8px 16px;
            background-color: #4a90e2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 5px;
        }
        .text-input-container button.cancel {
            background-color: #e74c3c;
        }
        .text-input-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .text-input-title {
            font-weight: bold;
        }
        .text-input-close {
            cursor: pointer;
            font-size: 20px;
            color: #999;
        }
        .text-input-close:hover {
            color: #333;
        }
        .text-input-buttons {
            margin-top: 15px;
            text-align: right;
        }
        
        /* 涂鸦、直线设置面板样式 */
        .doodle-settings, .line-settings {
            position: fixed;
            bottom: 80px;
            left: 10px;
            right: 10px;
            display: none;
            background-color: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 30px;
            z-index: 100;
            flex-direction: column;
            align-items: flex-start;
            color: white;
            overflow-x: auto;
            overflow-y: hidden;
            white-space: nowrap;
            scrollbar-width: none;
            -ms-overflow-style: none;
            max-width: calc(100vw - 20px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
		
		.doodle-settings::-webkit-scrollbar, 
		.line-settings::-webkit-scrollbar {
		    display: none;
		}
        
        /* 粗细选择器样式 */
        .brush-size-selector {
            display: flex;
            align-items: center;
            margin-bottom: 10px; /* 增加下边距分隔两行 */
            width: 100%;
        }
        
        /* 颜色选择器样式 */
        .color-selector {
            display: flex;
            align-items: center;
            width: 100%;
        }

        .brush-size-selector label, .color-selector label {
            margin-right: 10px;
            font-size: 14px;
            color: white;
            flex-shrink: 0;
        }
        
        .brush-size-btn {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: white;
            margin: 0 5px;
            cursor: pointer;
            border: 2px solid #ddd;
        }
        
        .brush-size-btn.selected {
            border: 2px solid #4a90e2;
        }
        
        .brush-size-btn.small {
            width: 10px;
            height: 10px;
        }
        
        .brush-size-btn.medium {
            width: 20px;
            height: 20px;
        }
        
        .brush-size-btn.large {
            width: 30px;
            height: 30px;
        }

        .color-option {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin: 0 5px;
            cursor: pointer;
            border: 2px solid #ddd;
        }
        
        .color-option.selected {
            border: 2px solid white;
        }
		
		/* 截图选框样式 */
		.crop-selection {
		    position: absolute;
		    border: 2px dashed rgba(0, 0, 255, 0.8);
		    background-color: rgba(0, 0, 255, 0.1);
		    pointer-events: none;
		    display: none;
		    z-index: 999;
		}
		
		/* 截图控制点样式 */
		.crop-handle {
		    position: absolute;
		    width: 10px;
		    height: 10px;
		    background-color: white;
		    border: 1px solid blue;
		    border-radius: 50%;
		    pointer-events: all;
		}
		
		.save-option {
		    margin: 0 8px;
		    padding: 10px 18px;
		    border: none;
		    border-radius: 20px;
		    background-color: #4a90e2;
		    color: white;
		    font-size: 14px;
		    cursor: pointer;
		    outline: none;
		    flex-shrink: 0;
		    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
		    transition: all 0.2s ease;
		}
		
		.save-option:hover {
		    transform: translateY(-2px);
		    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
		    background-color: #3a80d2;
		}
    </style>
</head>
<body>
    <div class="container">
        <canvas id="canvas"></canvas>
    </div>
    
    <div class="toolbar">
        <button id="reset-btn">视角复原</button>
        <button id="undo-btn" class="undo">撤回</button>
        <button id="clear-btn" class="clear">清空</button>
        <button id="add-text-btn">文字</button>
        <button id="add-shape-btn">图形</button>
        <button id="add-doodle-btn">涂鸦</button>
		<button id="crop-btn">截图</button>
		<button id="save-btn" class="save">保存</button>
		<button id="save-view-btn" class="save-option" style="display: none;">保存当前视图</button>
		<button id="save-full-btn" class="save-option" style="display: none;">保存完整图片</button>
		<button id="save-cancel-btn" class="delete" style="display: none;">取消保存</button>
		<button id="crop-confirm-btn" class="confirm" style="display: none;">确认截图</button>
		<button id="crop-cancel-btn" class="delete" style="display: none;">取消截图</button>
        <button id="confirm-btn" class="confirm" style="display: none;">确认</button>
        <button id="delete-btn" class="delete" style="display: none;">删除</button>
    </div>
    
    <div class="shape-selector" id="shape-selector" style="display: none;">
        <button id="add-arrow-btn" class="shape-btn">箭头</button>
		<button id="add-line-btn" class="shape-btn">直线</button>
        <button id="add-rect-btn" class="shape-btn">矩形</button>
        <button id="add-circle-btn" class="shape-btn">圆形</button>
    </div>
    
    <!-- 涂鸦设置面板 -->
    <div class="doodle-settings" id="doodle-settings">
        <div class="brush-size-selector">
            <label>粗细:</label>
            <div class="brush-size-btn small" data-size="2"></div>
            <div class="brush-size-btn medium selected" data-size="5"></div>
            <div class="brush-size-btn large" data-size="10"></div>
        </div>
        <div class="color-selector">
            <label>颜色:</label>
            <div class="color-option selected" style="background-color: red;" data-color="red"></div>
            <div class="color-option" style="background-color: blue;" data-color="blue"></div>
            <div class="color-option" style="background-color: green;" data-color="green"></div>
            <div class="color-option" style="background-color: black;" data-color="black"></div>
            <div class="color-option" style="background-color: yellow;" data-color="yellow"></div>
        </div>
    </div>
	
	<!-- 直线设置面板 -->
	<div class="line-settings" id="line-settings" style="display: none;">
	    <div class="brush-size-selector">
	        <label>粗细:</label>
	        <div class="brush-size-btn small" data-size="2"></div>
	        <div class="brush-size-btn medium selected" data-size="5"></div>
	        <div class="brush-size-btn large" data-size="10"></div>
	    </div>
	    <div class="color-selector">
	        <label>颜色:</label>
	        <div class="color-option selected" style="background-color: red;" data-color="red"></div>
	        <div class="color-option" style="background-color: blue;" data-color="blue"></div>
	        <div class="color-option" style="background-color: green;" data-color="green"></div>
	        <div class="color-option" style="background-color: black;" data-color="black"></div>
	        <div class="color-option" style="background-color: yellow;" data-color="yellow"></div>
	    </div>
	</div>
    
    <div class="text-input-container">
        <div class="text-input-header">
            <div class="text-input-title">添加文字</div>
            <div class="text-input-close" id="text-input-close-btn">×</div>
        </div>
        <input type="text" id="text-input" placeholder="输入文字内容">
        <div class="text-input-buttons">
            <button id="input-cancel-btn" class="cancel">取消</button>
            <button id="input-confirm-btn">确定</button>
        </div>
    </div>

    <script>
        // 状态变量
        let scale = 1;
        let offsetX = 0;
        let offsetY = 0;
        let isDragging = false;
        let isAddingText = false;
        let isAddingArrow = false;
        let isAddingRect = false;
        let isAddingCircle = false;
        let isAddingDoodle = false;
		let isAddingLine = false;
        let isEditing = false;
		let isCropping = false;
        let currentText = null;
        let currentArrow = null;
        let currentRect = null;
        let currentCircle = null;
		let currentLine = null;
		let cropSelection = null;
        let doodleStrokes = []; // 存储所有涂鸦笔画
        let currentDoodleStroke = []; // 当前正在绘制的笔画
        let textX = 0;
        let textY = 0;
        let textScale = 1;
        let startX, startY;
		let cropStartX, cropStartY;
		let cropEndX, cropEndY;
        let initialDistance;
        let img = new Image();
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        let initialTextScale = 1;
        let currentGestureScale = 1;
        let arrowSelectedEnd = null; // 'start' 或 'end' 表示选中的端点
        let rectSelectedCorner = null; // 'tl', 'tr', 'bl', 'br' 表示选中的角
        let circleSelectedPoint = null; // 'center', 'edge' 表示选中的点
        let arrowHitRadius = 10; // 端点点击检测半径
        let isAddingArrowMode = false;
        let isAddingRectMode = false;
        let isAddingCircleMode = false;
        let isAddingDoodleMode = false;
		let isAddingLineMode = false;
        let lastTouchTime = 0;
        let touchStartTimer = null;
        
        // 涂鸦设置
        let brushSize = 5; // 默认画笔粗细
        let brushColor = 'red'; // 默认画笔颜色
		
		// 直线设置
		let lineWidth = 3; // 默认直线粗细
		let lineColor = 'red'; // 默认直线颜色
        
        // 历史记录
        let history = [];
        const MAX_HISTORY = 50;
        let isRestoring = false;
        
        // 工具栏元素
        const resetBtn = document.getElementById('reset-btn');
        const undoBtn = document.getElementById('undo-btn');
        const clearBtn = document.getElementById('clear-btn');
        const addTextBtn = document.getElementById('add-text-btn');
        const addShapeBtn = document.getElementById('add-shape-btn');
        const addDoodleBtn = document.getElementById('add-doodle-btn');
		const addLineBtn = document.getElementById('add-line-btn');
		const screenshotBtn = document.getElementById('screenshot-btn');
        const confirmBtn = document.getElementById('confirm-btn');
        const deleteBtn = document.getElementById('delete-btn');
        const textInputContainer = document.querySelector('.text-input-container');
        const textInput = document.getElementById('text-input');
        const textInputCloseBtn = document.getElementById('text-input-close-btn');
        const inputCancelBtn = document.getElementById('input-cancel-btn');
        const inputConfirmBtn = document.getElementById('input-confirm-btn');
		const saveBtn = document.getElementById('save-btn');
        // 图形选择元素
        const shapeSelector = document.getElementById('shape-selector');
        const addArrowBtn = document.getElementById('add-arrow-btn');
        const addRectBtn = document.getElementById('add-rect-btn');
        const addCircleBtn = document.getElementById('add-circle-btn');
        // 涂鸦设置元素
        const doodleSettings = document.getElementById('doodle-settings');
        const brushSizeButtons = document.querySelectorAll('.brush-size-btn');
        const colorOptions = document.querySelectorAll('.color-option');
		// 直线设置元素
		const lineSettings = document.getElementById('line-settings');
		const lineSizeButtons = lineSettings.querySelectorAll('.brush-size-btn');
		const lineColorOptions = lineSettings.querySelectorAll('.color-option');

        // 添加清空按钮的事件监听器
        clearBtn.addEventListener('click', clearAll);
		
		function getQueryParam(name) {
		  const url = new URL(window.location.href);
		  return url.searchParams.get(name);
		}
		// 获取传递过来的图片URL
		const imageUrl = decodeURIComponent(getQueryParam('imageData'));
        
        // 清空所有操作的函数
        function clearAll() {
            // 清空历史记录
            history = [];
            
            // 重置所有状态变量
            isAddingText = false;
            isAddingArrow = false;
            isAddingRect = false;
            isAddingCircle = false;
            isAddingDoodle = false;
			isAddingLine = false;
            isEditing = false;
            currentText = null;
            currentArrow = null;
            currentRect = null;
            currentCircle = null;
			currentLine = null;
            doodleStrokes = [];
            currentDoodleStroke = [];
            isAddingDoodleMode = false;
            isAddingArrowMode = false;
            isAddingRectMode = false;
            isAddingCircleMode = false;
			isAddingLineMode = false;
            
            // 隐藏所有编辑相关的面板
            shapeSelector.style.display = 'none';
            doodleSettings.style.display = 'none';
			lineSettings.style.display = 'none';
            textInputContainer.style.display = 'none';
            
            // 重置工具栏显示
            toggleToolbar(false);
            
            // 重新加载原始图片
            img.src = imageUrl || '';
        }

        // 初始化Canvas
        function initCanvas() {
            resizeCanvas();
            img.onload = function() {
                drawCanvas();
                saveToHistory();
            };
            img.crossOrigin = "Anonymous";
            img.src = imageUrl || '';
			// 创建截图选框元素
			cropSelection = document.createElement('div');
			cropSelection.className = 'crop-selection';
			document.body.appendChild(cropSelection);
        }

        // 绘制箭头
        function drawArrow(ctx, fromX, fromY, toX, toY, color = 'red', width = 3, isEditing = false) {
            const headLength = 15;
            const angle = Math.atan2(toY - fromY, toX - fromX);
            
            // 绘制箭头线
            ctx.beginPath();
            ctx.moveTo(fromX, fromY);
            ctx.lineTo(toX, toY);
            ctx.strokeStyle = color;
            ctx.lineWidth = width;
            ctx.stroke();
            
            // 绘制箭头头部
            ctx.beginPath();
            ctx.moveTo(toX, toY);
            ctx.lineTo(
                toX - headLength * Math.cos(angle - Math.PI / 6),
                toY - headLength * Math.sin(angle - Math.PI / 6)
            );
            ctx.lineTo(
                toX - headLength * Math.cos(angle + Math.PI / 6),
                toY - headLength * Math.sin(angle + Math.PI / 6)
            );
            ctx.closePath();
            ctx.fillStyle = color;
            ctx.fill();
            
            // 如果是编辑模式，绘制可拖动的端点
            if (isEditing) {
                // 绘制起点端点
                ctx.beginPath();
                ctx.arc(fromX, fromY, arrowHitRadius, 0, Math.PI * 2);
                ctx.fillStyle = arrowSelectedEnd === 'start' ? '#4a90e2' : 'white';
                ctx.fill();
                ctx.strokeStyle = '#4a90e2';
                ctx.lineWidth = 2;
                ctx.stroke();
                
                // 绘制终点端点
                ctx.beginPath();
                ctx.arc(toX, toY, arrowHitRadius, 0, Math.PI * 2);
                ctx.fillStyle = arrowSelectedEnd === 'end' ? '#4a90e2' : 'white';
                ctx.fill();
                ctx.strokeStyle = '#4a90e2';
                ctx.lineWidth = 2;
                ctx.stroke();
            }
        }
		
		// 添加绘制直线的函数
		function drawLine(ctx, fromX, fromY, toX, toY, color = lineColor, width = lineWidth, isEditing = false) {
		    // 绘制直线
		    ctx.beginPath();
		    ctx.moveTo(fromX, fromY);
		    ctx.lineTo(toX, toY);
		    ctx.strokeStyle = color;
		    ctx.lineWidth = width;
		    ctx.stroke();
		    
		    // 如果是编辑模式，绘制可拖动的端点
		    if (isEditing) {
		        // 绘制起点端点
		        ctx.beginPath();
		        ctx.arc(fromX, fromY, arrowHitRadius, 0, Math.PI * 2);
		        ctx.fillStyle = arrowSelectedEnd === 'start' ? '#4a90e2' : 'white';
		        ctx.fill();
		        ctx.strokeStyle = '#4a90e2';
		        ctx.lineWidth = 2;
		        ctx.stroke();
		        
		        // 绘制终点端点
		        ctx.beginPath();
		        ctx.arc(toX, toY, arrowHitRadius, 0, Math.PI * 2);
		        ctx.fillStyle = arrowSelectedEnd === 'end' ? '#4a90e2' : 'white';
		        ctx.fill();
		        ctx.strokeStyle = '#4a90e2';
		        ctx.lineWidth = 2;
		        ctx.stroke();
		    }
		}

        // 绘制矩形
        function drawRect(ctx, x, y, width, height, color = 'red', lineWidth = 3, isEditing = false) {
            // 绘制矩形
            ctx.beginPath();
            ctx.rect(x, y, width, height);
            ctx.strokeStyle = color;
            ctx.lineWidth = lineWidth;
            ctx.stroke();
            
            // 如果是编辑模式，绘制可拖动的角点
            if (isEditing) {
                const corners = [
                    { x: x, y: y, type: 'tl' }, // 左上
                    { x: x + width, y: y, type: 'tr' }, // 右上
                    { x: x, y: y + height, type: 'bl' }, // 左下
                    { x: x + width, y: y + height, type: 'br' } // 右下
                ];
                
                corners.forEach(corner => {
                    ctx.beginPath();
                    ctx.arc(corner.x, corner.y, arrowHitRadius, 0, Math.PI * 2);
                    ctx.fillStyle = rectSelectedCorner === corner.type ? '#4a90e2' : 'white';
                    ctx.fill();
                    ctx.strokeStyle = '#4a90e2';
                    ctx.lineWidth = 2;
                    ctx.stroke();
                });
            }
        }

        // 绘制圆形
        function drawCircle(ctx, x, y, radius, color = 'red', lineWidth = 3, isEditing = false) {
            // 绘制圆形
            ctx.beginPath();
            ctx.arc(x, y, Math.abs(radius), 0, Math.PI * 2);
            ctx.strokeStyle = color;
            ctx.lineWidth = lineWidth;
            ctx.stroke();
            
            // 如果是编辑模式，绘制可拖动的控制点
            if (isEditing) {
                // 绘制中心点
                ctx.beginPath();
                ctx.arc(x, y, arrowHitRadius, 0, Math.PI * 2);
                ctx.fillStyle = circleSelectedPoint === 'center' ? '#4a90e2' : 'white';
                ctx.fill();
                ctx.strokeStyle = '#4a90e2';
                ctx.lineWidth = 2;
                ctx.stroke();
                
                // 绘制边缘点
                const edgeX = x + radius;
                const edgeY = y;
                ctx.beginPath();
                ctx.arc(edgeX, edgeY, arrowHitRadius, 0, Math.PI * 2);
                ctx.fillStyle = circleSelectedPoint === 'edge' ? '#4a90e2' : 'white';
                ctx.fill();
                ctx.strokeStyle = '#4a90e2';
                ctx.lineWidth = 2;
                ctx.stroke();
            }
        }
		
		// 开始截图
		function startCrop() {
			isCropping = true;
			isEditing = true;
			
			// 隐藏所有其他按钮，只显示截图相关按钮
			document.getElementById('reset-btn').style.display = 'none';
			document.getElementById('undo-btn').style.display = 'none';
			document.getElementById('clear-btn').style.display = 'none';
			document.getElementById('add-text-btn').style.display = 'none';
			document.getElementById('add-shape-btn').style.display = 'none';
			document.getElementById('add-doodle-btn').style.display = 'none';
			document.getElementById('crop-btn').style.display = 'none';
			document.getElementById('confirm-btn').style.display = 'none';
			document.getElementById('delete-btn').style.display = 'none';
			document.getElementById('save-btn').style.display = 'none';
			
			// 显示截图确认和取消按钮
			document.getElementById('crop-confirm-btn').style.display = 'block';
			document.getElementById('crop-cancel-btn').style.display = 'block';
			
			// 启用画布交互
			canvas.style.pointerEvents = 'auto';
			
			// 重置选框位置
			cropStartX = cropEndX = 0;
			cropStartY = cropEndY = 0;
			cropSelection.style.display = 'none';
		}
		
		// 更新截图选框
		function updateCropSelection() {
		    if (!isCropping) return;
		    
		    // 计算实际图片在画布上的位置和尺寸
		    const imgWidth = img.width * scale;
		    const imgHeight = img.height * scale;
		    const imgX = (canvas.width - imgWidth) / 2 + offsetX;
		    const imgY = (canvas.height - imgHeight) / 2 + offsetY;
		    
		    // 限制选框在图片范围内
		    const left = Math.max(imgX, Math.min(cropStartX, cropEndX));
		    const top = Math.max(imgY, Math.min(cropStartY, cropEndY));
		    const right = Math.min(imgX + imgWidth, Math.max(cropStartX, cropEndX));
		    const bottom = Math.min(imgY + imgHeight, Math.max(cropStartY, cropEndY));
		    
		    const width = right - left;
		    const height = bottom - top;
		    
		    cropSelection.style.display = 'block';
		    cropSelection.style.left = left + 'px';
		    cropSelection.style.top = top + 'px';
		    cropSelection.style.width = width + 'px';
		    cropSelection.style.height = height + 'px';
		}
		
		// 确认截图
		function confirmCrop() {
		    if (!isCropping) return;
		    
		    // 计算实际图片在画布上的位置和尺寸
		    const imgWidth = img.width * scale;
		    const imgHeight = img.height * scale;
		    const imgX = (canvas.width - imgWidth) / 2 + offsetX;
		    const imgY = (canvas.height - imgHeight) / 2 + offsetY;
		    
		    // 确保选框在图片范围内
		    const left = Math.max(imgX, Math.min(cropStartX, cropEndX));
		    const top = Math.max(imgY, Math.min(cropStartY, cropEndY));
		    const right = Math.min(imgX + imgWidth, Math.max(cropStartX, cropEndX));
		    const bottom = Math.min(imgY + imgHeight, Math.max(cropStartY, cropEndY));
		    
		    const width = right - left;
		    const height = bottom - top;
		    
		    if (width <= 0 || height <= 0) {
		        alert("请选择有效的截图区域");
		        return;
		    }
		    
		    // 创建临时canvas，尺寸与原始图片比例相同
		    const tempCanvas = document.createElement('canvas');
		    // 计算在原始图片上的选区
		    const srcX = (left - imgX) / scale;
		    const srcY = (top - imgY) / scale;
		    const srcWidth = width / scale;
		    const srcHeight = height / scale;
		    
		    tempCanvas.width = srcWidth;
		    tempCanvas.height = srcHeight;
		    const tempCtx = tempCanvas.getContext('2d');
		    
		    // 绘制选中区域（使用原始分辨率）
		    tempCtx.drawImage(img, srcX, srcY, srcWidth, srcHeight, 0, 0, srcWidth, srcHeight);
		    
		    // 更新图片但保持当前视图状态
		    const currentScale = scale;
		    const currentOffsetX = offsetX;
		    const currentOffsetY = offsetY;
		    
		    img.onload = function() {
		        // 恢复之前的缩放和偏移
		        scale = currentScale;
		        offsetX = currentOffsetX;
		        offsetY = currentOffsetY;
		        
		        // 重置状态
		        resetCrop();
		        saveToHistory();
		        drawCanvas();
		    };
		    img.src = tempCanvas.toDataURL('image/png');
		}
		
		// 取消截图
		function cancelCrop() {
		    resetCrop();
		    drawCanvas();
		}
		
		// 重置截图状态
		function resetCrop() {
			isCropping = false;
			isEditing = false;
			cropSelection.style.display = 'none';
			
			// 恢复按钮状态 - 显示常规工具栏按钮
			document.getElementById('reset-btn').style.display = 'block';
			document.getElementById('undo-btn').style.display = 'block';
			document.getElementById('clear-btn').style.display = 'block';
			document.getElementById('add-text-btn').style.display = 'block';
			document.getElementById('add-shape-btn').style.display = 'block';
			document.getElementById('add-doodle-btn').style.display = 'block';
			document.getElementById('crop-btn').style.display = 'block';
			document.getElementById('save-btn').style.display = 'block';
			
			// 隐藏截图相关按钮
			document.getElementById('crop-confirm-btn').style.display = 'none';
			document.getElementById('crop-cancel-btn').style.display = 'none';
			
			// 恢复画布交互
			canvas.style.pointerEvents = 'auto';
		}

        // 保存当前状态到历史记录
        function saveToHistory() {
            if (isRestoring) return;
            
            const tempCanvas = document.createElement('canvas');
            tempCanvas.width = img.width;
            tempCanvas.height = img.height;
            const tempCtx = tempCanvas.getContext('2d');
            tempCtx.drawImage(img, 0, 0);
            
            const state = tempCanvas.toDataURL('image/png');
            
            if (history.length === 0 || state !== history[history.length - 1]) {
                history.push(state);
                
                if (history.length > MAX_HISTORY) {
                    history.shift();
                }
            }
            
            updateUndoButton();
        }

        // 从历史记录恢复
        function restoreFromHistory() {
            if (history.length <= 1) return;
            
            isRestoring = true;
            history.pop();
            const lastState = history[history.length - 1];
            
            const tempImg = new Image();
            tempImg.onload = function() {
                // 清除当前编辑状态
                currentText = null;
                currentArrow = null;
                currentRect = null;
                currentCircle = null;
                doodleStrokes = [];
                currentDoodleStroke = [];
                isAddingText = false;
                isAddingArrow = false;
                isAddingRect = false;
                isAddingCircle = false;
                isAddingDoodle = false;
                isEditing = false;
                
                // 隐藏编辑面板
                shapeSelector.style.display = 'none';
                doodleSettings.style.display = 'none';
                textInputContainer.style.display = 'none';
                
                // 更新图片
                img.src = lastState;
                drawCanvas();
                isRestoring = false;
                updateUndoButton();
                toggleToolbar(false);
            };
            tempImg.src = lastState;
        }

        // 更新按钮状态
        function updateUndoButton() {
            undoBtn.disabled = history.length <= 1;
        }

        // 调整Canvas大小
        function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            drawCanvas();
        }

        // 绘制Canvas内容
        function drawCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
			
			// 使用imageSmoothingEnabled禁用平滑处理
			ctx.imageSmoothingEnabled = false;
			ctx.mozImageSmoothingEnabled = false;
			ctx.webkitImageSmoothingEnabled = false;
			ctx.msImageSmoothingEnabled = false;
            
            const imgWidth = Math.floor(img.width * scale);
            const imgHeight = Math.floor(img.height * scale);
            const imgX = Math.floor((canvas.width - imgWidth) / 2 + offsetX);
            const imgY = Math.floor((canvas.height - imgHeight) / 2 + offsetY);
            
            ctx.drawImage(img, 0, 0, img.width, img.height, imgX, imgY, imgWidth, imgHeight);
            
            if (isAddingText && currentText) {
                ctx.save();
                ctx.font = `${24 * textScale}px Arial`;
                ctx.fillStyle = 'red';
                ctx.fillText(currentText, textX, textY);
                ctx.restore();
            }
            
            if (isAddingArrow && currentArrow) {
                // 只有在编辑模式下才显示端点
                drawArrow(ctx, currentArrow.startX, currentArrow.startY, 
                         currentArrow.endX, currentArrow.endY, 'red', 3, isEditing);
            }
            
            if (isAddingRect && currentRect) {
                // 只有在编辑模式下才显示角点
                drawRect(ctx, currentRect.x, currentRect.y, 
                         currentRect.width, currentRect.height, 'red', 3, isEditing);
            }
            
            if (isAddingCircle && currentCircle) {
                // 只有在编辑模式下才显示控制点
                drawCircle(ctx, currentCircle.x, currentCircle.y, 
                         currentCircle.radius, 'red', 3, isEditing);
            }
			
			if (isAddingLine && currentLine) {
			    // 使用直线对象中保存的颜色和粗细，如果没有则使用默认值
			    drawLine(ctx, currentLine.startX, currentLine.startY, 
			             currentLine.endX, currentLine.endY, 
			             currentLine.color || lineColor, 
			             currentLine.width || lineWidth, 
			             isEditing);
			}

            // 绘制涂鸦
            if (isAddingDoodle) {
                // 绘制已完成的笔画
                doodleStrokes.forEach(stroke => {
                    if (stroke.length > 0) {
                        ctx.beginPath();
                        ctx.moveTo(stroke[0].x, stroke[0].y);
                        for (let i = 1; i < stroke.length; i++) {
                            ctx.lineTo(stroke[i].x, stroke[i].y);
                        }
                        ctx.strokeStyle = stroke.color || brushColor;
                        ctx.lineWidth = stroke.size || brushSize;
                        ctx.lineCap = 'round';
                        ctx.lineJoin = 'round';
                        ctx.stroke();
                    }
                });
                
                // 绘制当前正在绘制的笔画
                if (currentDoodleStroke.length > 0) {
                    ctx.beginPath();
                    ctx.moveTo(currentDoodleStroke[0].x, currentDoodleStroke[0].y);
                    for (let i = 1; i < currentDoodleStroke.length; i++) {
                        ctx.lineTo(currentDoodleStroke[i].x, currentDoodleStroke[i].y);
                    }
                    ctx.strokeStyle = currentDoodleStroke.color || brushColor;
                    ctx.lineWidth = currentDoodleStroke.size || brushSize;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    ctx.stroke();
                }
            }
        }

        // 初始化图片位置
        function initImage() {
            scale = Math.min(
                canvas.width / img.width,
                canvas.height / img.height,
                1
            );
            offsetX = 0;
            offsetY = 0;
            drawCanvas();
            saveToHistory(); // 保存初始状态到历史记录
        }

        // 切换工具栏状态
        function toggleToolbar(isEditing) {
            if (isEditing) {
                addTextBtn.style.display = 'none';
                addShapeBtn.style.display = 'none';
                addDoodleBtn.style.display = 'none';
                resetBtn.style.display = 'none';
                undoBtn.style.display = 'none';
                clearBtn.style.display = 'none';  // 新增：隐藏清空按钮
                document.getElementById('crop-btn').style.display = 'none';  // 新增：隐藏截图按钮
				saveBtn.style.display = 'none';
                confirmBtn.style.display = 'block';
                deleteBtn.style.display = 'block';
                shapeSelector.style.display = 'none';
            } else {
                addTextBtn.style.display = 'block';
                addShapeBtn.style.display = 'block';
                addDoodleBtn.style.display = 'block';
                resetBtn.style.display = 'block';
                undoBtn.style.display = 'block';
                clearBtn.style.display = 'block';  // 新增：显示清空按钮
                document.getElementById('crop-btn').style.display = 'block';  // 新增：显示截图按钮
				saveBtn.style.display = 'block';
                confirmBtn.style.display = 'none';
                deleteBtn.style.display = 'none';
                shapeSelector.style.display = 'none';
                doodleSettings.style.display = 'none'; // 隐藏涂鸦设置面板
            }
        }

        // 事件处理
        canvas.addEventListener('mousedown', handleStart);
        canvas.addEventListener('touchstart', handleStart);
        canvas.addEventListener('mousemove', handleMove);
        canvas.addEventListener('touchmove', handleMove);
        canvas.addEventListener('mouseup', handleEnd);
        canvas.addEventListener('touchend', handleEnd);
        canvas.addEventListener('wheel', handleWheel);
        
        function handleStart(e) {
            if (isAddingArrow && !currentArrow) {
                return; // 如果正在添加箭头但还没有初始化起点，让上面的监听器处理
            }
            if (isAddingRect && !currentRect) {
                return; // 如果正在添加矩形但还没有初始化起点，让上面的监听器处理
            }
            if (isAddingCircle && !currentCircle) {
                return; // 如果正在添加圆形但还没有初始化起点，让上面的监听器处理
            }
			if (isAddingLine && !currentLine) {
			    return; // 如果正在添加圆形但还没有初始化起点，让上面的监听器处理
			}
            // 在添加图形时禁用双指缩放
            if (isAddingArrowMode || isAddingRectMode || isAddingCircleMode || isAddingDoodleMode || isAddingLineMode) {
                clearTimeout(touchStartTimer);
                if (e.touches.length > 1) {
                    e.preventDefault();
                    return;
                }
            }
            e.preventDefault();
            const isTouch = e.type === 'touchstart';
            const x = isTouch ? e.touches[0].clientX : e.clientX;
            const y = isTouch ? e.touches[0].clientY : e.clientY;
            
            // 涂鸦处理
            if (isAddingDoodle) {
                isEditing = true;
                currentDoodleStroke = [{x: x, y: y}]; // 开始新的笔画
                // 为当前笔画设置颜色和粗细属性
                currentDoodleStroke.color = brushColor;
                currentDoodleStroke.size = brushSize;
                drawCanvas();
            }
            // 文本处理
            else if (isAddingText) {
                if (isTouch && e.touches.length === 2) {
                    const touch1 = e.touches[0];
                    const touch2 = e.touches[1];
                    initialDistance = Math.hypot(
                        touch2.clientX - touch1.clientX,
                        touch2.clientY - touch1.clientY
                    );
                    initialTextScale = textScale;
                    currentGestureScale = 1;
                } else {
                    isEditing = true;
                    startX = x - textX;
                    startY = y - textY;
                }
            } 
            // 箭头处理
            else if (isAddingArrow && currentArrow) {
                // 检查是否点击了箭头的端点或线
                const distToStart = Math.hypot(x - currentArrow.startX, y - currentArrow.startY);
                const distToEnd = Math.hypot(x - currentArrow.endX, y - currentArrow.endY);
                
                if (distToStart <= arrowHitRadius) {
                    arrowSelectedEnd = 'start';
                    isEditing = true;
                } else if (distToEnd <= arrowHitRadius) {
                    arrowSelectedEnd = 'end';
                    isEditing = true;
                } else if (isPointOnLine(x, y, currentArrow.startX, currentArrow.startY, 
                                      currentArrow.endX, currentArrow.endY, 5)) {
                    // 点击了箭头线，可以拖动整个箭头
                    arrowSelectedEnd = null;
                    isEditing = true;
                    startX = x - currentArrow.startX;
                    startY = y - currentArrow.startY;
                } else {
                    // 点击了箭头以外的区域，移动整个箭头
                    isEditing = true;
                    startX = x - currentArrow.startX;
                    startY = y - currentArrow.startY;
                }
            }
			// 直线处理
			else if (isAddingLine && currentLine) {
			    // 检查是否点击了直线的端点或线
			    const distToStart = Math.hypot(x - currentLine.startX, y - currentLine.startY);
			    const distToEnd = Math.hypot(x - currentLine.endX, y - currentLine.endY);
			    
			    if (distToStart <= arrowHitRadius) {
			        arrowSelectedEnd = 'start';
			        isEditing = true;
			    } else if (distToEnd <= arrowHitRadius) {
			        arrowSelectedEnd = 'end';
			        isEditing = true;
			    } else if (isPointOnLine(x, y, currentLine.startX, currentLine.startY, 
			                          currentLine.endX, currentLine.endY, 5)) {
			        // 点击了直线线，可以拖动整个直线
			        arrowSelectedEnd = null;
			        isEditing = true;
			        startX = x - currentLine.startX;
			        startY = y - currentLine.startY;
			    } else {
			        // 点击了直线以外的区域，移动整个直线
			        isEditing = true;
			        startX = x - currentLine.startX;
			        startY = y - currentLine.startY;
			    }
			}
            // 矩形处理
            else if (isAddingRect && currentRect) {
                // 检查是否点击了矩形的角点
                const corners = [
                    { x: currentRect.x, y: currentRect.y, type: 'tl' }, // 左上
                    { x: currentRect.x + currentRect.width, y: currentRect.y, type: 'tr' }, // 右上
                    { x: currentRect.x, y: currentRect.y + currentRect.height, type: 'bl' }, // 左下
                    { x: currentRect.x + currentRect.width, y: currentRect.y + currentRect.height, type: 'br' } // 右下
                ];
                
                let cornerClicked = false;
                for (const corner of corners) {
                    if (Math.hypot(x - corner.x, y - corner.y) <= arrowHitRadius) {
                        rectSelectedCorner = corner.type;
                        isEditing = true;
                        cornerClicked = true;
                        break;
                    }
                }
                
                // 如果点击了矩形内部但没有点击角点，可以拖动整个矩形
                if (!cornerClicked && 
                    x >= currentRect.x && x <= currentRect.x + currentRect.width &&
                    y >= currentRect.y && y <= currentRect.y + currentRect.height) {
                    isEditing = true;
                    startX = x - currentRect.x;
                    startY = y - currentRect.y;
                } else if (!cornerClicked) {
                    // 点击了矩形以外的区域，移动整个矩形
                    isEditing = true;
                    startX = x - currentRect.x;
                    startY = y - currentRect.y;
                }
            }
            // 圆形处理
            else if (isAddingCircle && currentCircle) {
                // 检查是否点击了圆形的控制点
                const distToCenter = Math.hypot(x - currentCircle.x, y - currentCircle.y);
                const distToEdge = Math.hypot(x - (currentCircle.x + currentCircle.radius), y - currentCircle.y);
                
                if (distToCenter <= arrowHitRadius) {
                    circleSelectedPoint = 'center';
                    isEditing = true;
                } else if (distToEdge <= arrowHitRadius) {
                    circleSelectedPoint = 'edge';
                    isEditing = true;
                } else if (distToCenter <= Math.abs(currentCircle.radius)) {
                    // 点击了圆形内部，可以拖动整个圆形
                    circleSelectedPoint = null;
                    isEditing = true;
                    startX = x - currentCircle.x;
                    startY = y - currentCircle.y;
                } else {
                    // 点击了圆形以外的区域，移动整个圆形
                    isEditing = true;
                    startX = x - currentCircle.x;
                    startY = y - currentCircle.y;
                }
            }
			else if (isCropping) {
				e.preventDefault();
				const isTouch = e.type === 'touchstart';
				const x = isTouch ? e.touches[0].clientX : e.clientX;
				const y = isTouch ? e.touches[0].clientY : e.clientY;
				
				cropStartX = cropEndX = x;
				cropStartY = cropEndY = y;
				updateCropSelection();
			}
            else {
                if (isTouch && e.touches.length === 2) {
                    const touch1 = e.touches[0];
                    const touch2 = e.touches[1];
                    initialDistance = Math.hypot(
                        touch2.clientX - touch1.clientX,
                        touch2.clientY - touch1.clientY
                    );
                } else {
                    isDragging = true;
                    startX = x - offsetX;
                    startY = y - offsetY;
                }
            }
        }
        
        // 检测点是否在线段上
        function isPointOnLine(px, py, x1, y1, x2, y2, tolerance) {
            const d1 = Math.hypot(px - x1, py - y1);
            const d2 = Math.hypot(px - x2, py - y2);
            const lineLength = Math.hypot(x2 - x1, y2 - y1);
            
            // 如果点到两端点的距离之和与线段长度的差小于容差，则认为点在线上
            return Math.abs(d1 + d2 - lineLength) < tolerance;
        }

        function handleMove(e) {
            if ((isAddingArrow && !currentArrow) || (isAddingRect && !currentRect) || (isAddingCircle && !currentCircle) || (isAddingLine && !currentLine)) return;
            e.preventDefault();
            const isTouch = e.type === 'touchmove';
            const x = isTouch ? e.touches[0].clientX : e.clientX;
            const y = isTouch ? e.touches[0].clientY : e.clientY;
            // 在添加图形时禁用双指缩放
            if ((isAddingArrow || isAddingRect || isAddingCircle || isAddingDoodle || isAddingLine) && e.touches && e.touches.length > 1) {
                e.preventDefault();
                return;
            }
            
            // 涂鸦处理
            if (isAddingDoodle) {
                currentDoodleStroke.push({x: x, y: y, color: brushColor, size: brushSize});
                drawCanvas();
            }
            else if (isAddingArrow && currentArrow) {
                if (!isEditing) {
                    // 正在绘制新箭头，更新终点位置
                    currentArrow.endX = x;
                    currentArrow.endY = y;
                } else {
                    // 编辑已有箭头
                    if (arrowSelectedEnd === 'start') {
                        currentArrow.startX = x;
                        currentArrow.startY = y;
                    } else if (arrowSelectedEnd === 'end') {
                        currentArrow.endX = x;
                        currentArrow.endY = y;
                    } else {
                        // 拖动整个箭头
                        const dx = x - startX - currentArrow.startX;
                        const dy = y - startY - currentArrow.startY;
                        currentArrow.startX = x - startX;
                        currentArrow.startY = y - startY;
                        currentArrow.endX += dx;
                        currentArrow.endY += dy;
                    }
                }
                drawCanvas();
            }
			else if (isAddingLine && currentLine) {
			    if (!isEditing) {
			        // 正在绘制新直线，更新终点位置
			        currentLine.endX = x;
			        currentLine.endY = y;
			    } else {
			        // 编辑已有直线
			        if (arrowSelectedEnd === 'start') {
			            currentLine.startX = x;
			            currentLine.startY = y;
			        } else if (arrowSelectedEnd === 'end') {
			            currentLine.endX = x;
			            currentLine.endY = y;
			        } else {
			            // 拖动整个直线
			            const dx = x - startX - currentLine.startX;
			            const dy = y - startY - currentLine.startY;
			            currentLine.startX = x - startX;
			            currentLine.startY = y - startY;
			            currentLine.endX += dx;
			            currentLine.endY += dy;
			        }
			    }
			    drawCanvas();
			}
            else if (isAddingRect && currentRect) {
                if (!isEditing) {
                    // 正在绘制新矩形，更新宽度和高度
                    currentRect.width = x - currentRect.x;
                    currentRect.height = y - currentRect.y;
                } else {
                    // 编辑已有矩形
                    if (rectSelectedCorner) {
                        // 调整选中的角点
                        switch (rectSelectedCorner) {
                            case 'tl': // 左上角
                                currentRect.width += currentRect.x - x;
                                currentRect.height += currentRect.y - y;
                                currentRect.x = x;
                                currentRect.y = y;
                                break;
                            case 'tr': // 右上角
                                currentRect.width = x - currentRect.x;
                                currentRect.height += currentRect.y - y;
                                currentRect.y = y;
                                break;
                            case 'bl': // 左下角
                                currentRect.width += currentRect.x - x;
                                currentRect.height = y - currentRect.y;
                                currentRect.x = x;
                                break;
                            case 'br': // 右下角
                                currentRect.width = x - currentRect.x;
                                currentRect.height = y - currentRect.y;
                                break;
                        }
                    } else {
                        // 拖动整个矩形
                        currentRect.x = x - startX;
                        currentRect.y = y - startY;
                    }
                }
                drawCanvas();
            }
            else if (isAddingCircle && currentCircle) {
                if (!isEditing) {
                    // 正在绘制新圆形，更新半径
                    currentCircle.radius = Math.sqrt(Math.pow(x - currentCircle.x, 2) + Math.pow(y - currentCircle.y, 2));
                } else {
                    // 编辑已有圆形
                    if (circleSelectedPoint === 'center') {
                        // 移动中心点
                        currentCircle.x = x;
                        currentCircle.y = y;
                        // 边缘点也相应移动
                        const angle = Math.atan2(currentCircle.y - y, currentCircle.x - x);
                        const edgeX = x + currentCircle.radius * Math.cos(angle);
                        const edgeY = y + currentCircle.radius * Math.sin(angle);
                    } else if (circleSelectedPoint === 'edge') {
                        // 调整半径
                        currentCircle.radius = Math.sqrt(Math.pow(x - currentCircle.x, 2) + Math.pow(y - currentCircle.y, 2));
                    } else {
                        // 拖动整个圆形
                        currentCircle.x = x - startX;
                        currentCircle.y = y - startY;
                    }
                }
                drawCanvas();
            }
            else if (isAddingText) {
                if (isTouch && e.touches.length === 2) {
                    const touch1 = e.touches[0];
                    const touch2 = e.touches[1];
                    const currentDistance = Math.hypot(
                        touch2.clientX - touch1.clientX,
                        touch2.clientY - touch1.clientY
                    );
                    
                    if (initialDistance) {
                        const gestureScale = currentDistance / initialDistance;
                        let newScale = initialTextScale * gestureScale;
                        newScale = Math.max(0.5, Math.min(newScale, 3));
                        if (Math.abs(newScale - textScale) > 0.01) {
                            textScale = newScale;
                            currentGestureScale = gestureScale;
                            drawCanvas();
                        }
                    }
                } else if (isEditing) {
                    textX = x - startX;
                    textY = y - startY;
                    drawCanvas();
                }
            }
			else if (isCropping && cropStartX !== null) {
				e.preventDefault();
				const isTouch = e.type === 'touchmove';
				const x = isTouch ? e.touches[0].clientX : e.clientX;
				const y = isTouch ? e.touches[0].clientY : e.clientY;
				
				cropEndX = x;
				cropEndY = y;
				updateCropSelection();
			}
            else {
                if (isTouch && e.touches.length === 2) {
                    const touch1 = e.touches[0];
                    const touch2 = e.touches[1];
                    const currentDistance = Math.hypot(
                        touch2.clientX - touch1.clientX,
                        touch2.clientY - touch1.clientY
                    );
                    
                    scale = Math.max(0.1, Math.min(scale * (currentDistance / initialDistance), 5));
                    initialDistance = currentDistance;
                    drawCanvas();
                } else if (isDragging) {
                    offsetX = x - startX;
                    offsetY = y - startY;
                    drawCanvas();
                }
            }
        }

        function handleEnd(e) {
            e.preventDefault();
            
            if (isAddingArrow && currentArrow && !isEditing) {
                // 第一次释放鼠标（确定终点）后进入编辑模式
                isEditing = true;
                drawCanvas();
            }
            
            if (isAddingRect && currentRect && !isEditing) {
                // 第一次释放鼠标（确定大小）后进入编辑模式
                isEditing = true;
                drawCanvas();
            }
            
            if (isAddingCircle && currentCircle && !isEditing) {
                // 第一次释放鼠标（确定大小）后进入编辑模式
                isEditing = true;
                drawCanvas();
            }
			
			if (isAddingLine && currentLine && !isEditing) {
			    // 第一次释放鼠标（确定终点）后进入编辑模式
			    isEditing = true;
			    drawCanvas();
			}

            // 涂鸦处理
            if (isAddingDoodle && currentDoodleStroke.length > 0) {
                // 将当前笔画添加到已完成的笔画列表中
                const strokeToSave = [...currentDoodleStroke];
                strokeToSave.color = currentDoodleStroke.color;
                strokeToSave.size = currentDoodleStroke.size;
                doodleStrokes.push(strokeToSave);
                currentDoodleStroke = []; // 清空当前笔画，准备下一笔
                drawCanvas();
            }
			
			// 截图
			if (isCropping) {
				// 确保选框有足够大小
				if (Math.abs(cropEndX - cropStartX) < 10 || Math.abs(cropEndY - cropStartY) < 10) {
					cropSelection.style.display = 'none';
				}
			}
            
            isDragging = false;
            initialDistance = 0;
            currentGestureScale = 1;
            arrowSelectedEnd = null;
            rectSelectedCorner = null;
            circleSelectedPoint = null;
        }

        function handleWheel(e) {
            // 如果处于文字添加模式或图形模式（箭头、矩形、圆形、涂鸦），则不执行缩放
            if (isAddingText || isAddingArrowMode || isAddingRectMode || isAddingCircleMode || isAddingDoodleMode) return;
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            scale = Math.max(0.1, Math.min(scale * delta, 5));
            drawCanvas();
        }

        // 点击添加文字
        addTextBtn.addEventListener('click', () => {
            isAddingText = true;
            isAddingArrow = false;
            isAddingRect = false;
            isAddingCircle = false;
            textInputContainer.style.display = 'block';
            textInput.value = '';
            textInput.focus();
            toggleToolbar(false);
            // 禁用其他按钮
            addShapeBtn.disabled = true;
            addDoodleBtn.disabled = true;
            resetBtn.disabled = true;
            undoBtn.disabled = true;
			clearBtn.disabled = true;
			// 禁用截图按钮
			document.getElementById('crop-btn').disabled = true;
        });

        // 点击添加涂鸦
        addDoodleBtn.addEventListener('click', () => {
            isAddingDoodle = true;
            isAddingDoodleMode = true;
            isAddingText = false;
            isAddingArrow = false;
            isAddingRect = false;
            isAddingCircle = false;
            doodleStrokes = []; // 清空所有已完成的笔画
            currentDoodleStroke = []; // 清空当前笔画
            toggleToolbar(true);
            doodleSettings.style.display = 'flex'; // 显示涂鸦设置面板
            
            // 完全禁用画布的所有触摸手势
            canvas.style.touchAction = 'none';
        });

        // 点击添加图形
        addShapeBtn.addEventListener('click', () => {
			// 如果图形选择面板已经显示，则隐藏它
			if (shapeSelector.style.display === 'flex') {
				shapeSelector.style.display = 'none';
			} else {
				// 否则显示图形选择面板
				shapeSelector.style.display = 'flex';
			}
        });

        // 点击添加箭头
        addArrowBtn.addEventListener('click', () => {
            isAddingArrow = true;
            isAddingArrowMode = true;
            isAddingText = false;
            isAddingRect = false;
            isAddingCircle = false;
            currentArrow = null;
            shapeSelector.style.display = 'none';
            toggleToolbar(true);
            
            // 完全禁用画布的所有触摸手势
            canvas.style.touchAction = 'none';
            
            // 添加一次性起点监听器（带延迟检测）
            const initArrowStart = (e) => {
                // 如果是双指操作，直接返回
                if (e.touches && e.touches.length > 1) {
                    clearTimeout(touchStartTimer);
                    return;
                }
                
                // 防止快速连续触发
                const now = Date.now();
                if (now - lastTouchTime < 300) {
                    return;
                }
                lastTouchTime = now;
                
                // 延迟检测，确保不是双指操作的一部分
                touchStartTimer = setTimeout(() => {
                    const x = e.touches ? e.touches[0].clientX : e.clientX;
                    const y = e.touches ? e.touches[0].clientY : e.clientY;
                    
                    currentArrow = {
                        startX: x,
                        startY: y,
                        endX: x,
                        endY: y
                    };
                    
                    // 移除一次性监听器
                    canvas.removeEventListener('mousedown', initArrowStart);
                    canvas.removeEventListener('touchstart', initArrowStart);
                    
                    e.stopPropagation();
                    e.preventDefault();
                }, 100); // 100ms延迟检测
            };
            
            canvas.addEventListener('mousedown', initArrowStart);
            canvas.addEventListener('touchstart', initArrowStart);
        });
		
		// 添加直线
		addLineBtn.addEventListener('click', () => {
		    isAddingLine = true;
		    isAddingLineMode = true;
		    isAddingText = false;
		    isAddingArrow = false;
		    isAddingRect = false;
		    isAddingCircle = false;
		    currentLine = null;
		    shapeSelector.style.display = 'none';
		    toggleToolbar(true);
			lineSettings.style.display = 'flex'; // 显示直线设置面板
		    
		    // 完全禁用画布的所有触摸手势
		    canvas.style.touchAction = 'none';
		    
		    // 添加一次性起点监听器（带延迟检测）
		    const initLineStart = (e) => {
		        // 如果是双指操作，直接返回
		        if (e.touches && e.touches.length > 1) {
		            clearTimeout(touchStartTimer);
		            return;
		        }
		        
		        // 防止快速连续触发
		        const now = Date.now();
		        if (now - lastTouchTime < 300) {
		            return;
		        }
		        lastTouchTime = now;
		        
		        // 延迟检测，确保不是双指操作的一部分
		        touchStartTimer = setTimeout(() => {
		            const x = e.touches ? e.touches[0].clientX : e.clientX;
		            const y = e.touches ? e.touches[0].clientY : e.clientY;
		            
		            currentLine = {
		                startX: x,
		                startY: y,
		                endX: x,
		                endY: y,
						color: lineColor,  // 保存当前颜色
						width: lineWidth  // 保存当前粗细
		            };
		            
		            // 移除一次性监听器
		            canvas.removeEventListener('mousedown', initLineStart);
		            canvas.removeEventListener('touchstart', initLineStart);
		            
		            e.stopPropagation();
		            e.preventDefault();
		        }, 100); // 100ms延迟检测
		    };
		    
		    canvas.addEventListener('mousedown', initLineStart);
		    canvas.addEventListener('touchstart', initLineStart);
		});

        // 点击添加矩形
        addRectBtn.addEventListener('click', () => {
            isAddingRect = true;
            isAddingRectMode = true;
            isAddingText = false;
            isAddingArrow = false;
            isAddingCircle = false;
            currentRect = null;
            shapeSelector.style.display = 'none';
            toggleToolbar(true);
            
            // 完全禁用画布的所有触摸手势
            canvas.style.touchAction = 'none';
            
            // 添加一次性起点监听器（带延迟检测）
            const initRectStart = (e) => {
                // 如果是双指操作，直接返回
                if (e.touches && e.touches.length > 1) {
                    clearTimeout(touchStartTimer);
                    return;
                }
                
                // 防止快速连续触发
                const now = Date.now();
                if (now - lastTouchTime < 300) {
                    return;
                }
                lastTouchTime = now;
                
                // 延迟检测，确保不是双指操作的一部分
                touchStartTimer = setTimeout(() => {
                    const x = e.touches ? e.touches[0].clientX : e.clientX;
                    const y = e.touches ? e.touches[0].clientY : e.clientY;
                    
                    currentRect = {
                        x: x,
                        y: y,
                        width: 0,
                        height: 0
                    };
                    
                    // 移除一次性监听器
                    canvas.removeEventListener('mousedown', initRectStart);
                    canvas.removeEventListener('touchstart', initRectStart);
                    
                    e.stopPropagation();
                    e.preventDefault();
                }, 100); // 100ms延迟检测
            };
            
            canvas.addEventListener('mousedown', initRectStart);
            canvas.addEventListener('touchstart', initRectStart);
        });

        // 点击添加圆形
        addCircleBtn.addEventListener('click', () => {
            isAddingCircle = true;
            isAddingCircleMode = true;
            isAddingText = false;
            isAddingArrow = false;
            isAddingRect = false;
            currentCircle = null;
            shapeSelector.style.display = 'none';
            toggleToolbar(true);
            
            // 完全禁用画布的所有触摸手势
            canvas.style.touchAction = 'none';
            
            // 添加一次性起点监听器（带延迟检测）
            const initCircleStart = (e) => {
                // 如果是双指操作，直接返回
                if (e.touches && e.touches.length > 1) {
                    clearTimeout(touchStartTimer);
                    return;
                }
                
                // 防止快速连续触发
                const now = Date.now();
                if (now - lastTouchTime < 300) {
                    return;
                }
                lastTouchTime = now;
                
                // 延迟检测，确保不是双指操作的一部分
                touchStartTimer = setTimeout(() => {
                    const x = e.touches ? e.touches[0].clientX : e.clientX;
                    const y = e.touches ? e.touches[0].clientY : e.clientY;
                    
                    currentCircle = {
                        x: x,
                        y: y,
                        radius: 0
                    };
                    
                    // 移除一次性监听器
                    canvas.removeEventListener('mousedown', initCircleStart);
                    canvas.removeEventListener('touchstart', initCircleStart);
                    
                    e.stopPropagation();
                    e.preventDefault();
                }, 100); // 100ms延迟检测
            };
            
            canvas.addEventListener('mousedown', initCircleStart);
            canvas.addEventListener('touchstart', initCircleStart);
        });

        // 关闭文本输入
        function closeTextInput() {
            textInputContainer.style.display = 'none';
            isAddingText = false;
            currentText = null;
            toggleToolbar(false);
            // 启用其他按钮
            addShapeBtn.disabled = false;
            addDoodleBtn.disabled = false;
            resetBtn.disabled = false;
            undoBtn.disabled = false;
			clearBtn.disabled = false;
			// 禁用截图按钮
			document.getElementById('crop-btn').disabled = false;
        }

        textInputCloseBtn.addEventListener('click', closeTextInput);
        inputCancelBtn.addEventListener('click', closeTextInput);

        // 确认输入文字
        inputConfirmBtn.addEventListener('click', () => {
            const text = textInput.value.trim();
            if (text) {
                currentText = text;
                textX = canvas.width / 2;
                textY = canvas.height / 2;
                textScale = 1;
                textInput.value = '';
                textInputContainer.style.display = 'none';
                toggleToolbar(true);
                drawCanvas();
				// 启用其他按钮
				addShapeBtn.disabled = false;
				addDoodleBtn.disabled = false;
				resetBtn.disabled = false;
				undoBtn.disabled = false;
				clearBtn.disabled = false;
				// 禁用截图按钮
				document.getElementById('crop-btn').disabled = false;
            }
        });
        
        // 涂鸦设置面板中的画笔粗细选择
        brushSizeButtons.forEach(button => {
            button.addEventListener('click', function() {
                // 更新选中状态
                brushSizeButtons.forEach(btn => btn.classList.remove('selected'));
                this.classList.add('selected');
                
                // 设置画笔粗细
                brushSize = parseInt(this.dataset.size);
            });
        });
        
        // 涂鸦设置面板中的颜色选择
        colorOptions.forEach(option => {
            option.addEventListener('click', function() {
                // 更新选中状态
                colorOptions.forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');
                
                // 设置画笔颜色
                brushColor = this.dataset.color;
            });
        });
		
		// 直线设置面板中的粗细选择
		lineSizeButtons.forEach(button => {
		    button.addEventListener('click', function() {
		        // 更新选中状态
		        lineSizeButtons.forEach(btn => btn.classList.remove('selected'));
		        this.classList.add('selected');
		        
		        // 设置直线粗细
		        lineWidth = parseInt(this.dataset.size);
		        
		        // 如果正在编辑直线，更新当前直线的粗细
		        if (currentLine) {
		            currentLine.width = lineWidth;
		            drawCanvas();
		        }
		    });
		});
		
		// 直线设置面板中的颜色选择
		lineColorOptions.forEach(option => {
		    option.addEventListener('click', function() {
		        // 更新选中状态
		        lineColorOptions.forEach(opt => opt.classList.remove('selected'));
		        this.classList.add('selected');
		        
		        // 设置直线颜色
		        lineColor = this.dataset.color;
		        
		        // 如果正在编辑直线，更新当前直线的颜色
		        if (currentLine) {
		            currentLine.color = lineColor;
		            drawCanvas();
		        }
		    });
		});
        
        // 恢复触摸操作的函数
        function restoreTouchActions() {
            // 重置图形模式状态
            isAddingArrowMode = isAddingRectMode = isAddingCircleMode = isAddingDoodleMode = isAddingLineMode = false;
            clearTimeout(touchStartTimer);
            canvas.style.touchAction = '';
        }

        // 确认当前编辑
        confirmBtn.addEventListener('click', function() {
            // 恢复触摸操作
            restoreTouchActions();
			if ((isAddingText && currentText) || (isAddingArrow && currentArrow) || (isAddingRect && currentRect) || (isAddingCircle && currentCircle) || (isAddingDoodle && (doodleStrokes.length > 0 || currentDoodleStroke.length > 0)) || (isAddingLine && currentLine)) {
				saveToHistory();
                
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = img.width;
                tempCanvas.height = img.height;
                const tempCtx = tempCanvas.getContext('2d');
                tempCtx.drawImage(img, 0, 0);
                
                const imgWidth = img.width * scale;
                const imgHeight = img.height * scale;
                const imgX = (canvas.width - imgWidth) / 2 + offsetX;
                const imgY = (canvas.height - imgHeight) / 2 + offsetY;
                
                if (isAddingText && currentText) {
                    const relativeX = (textX - imgX) / scale;
                    const relativeY = (textY - imgY) / scale;
                    const finalTextSize = 24 * textScale / scale;
                    
                    tempCtx.font = `${finalTextSize}px Arial`;
                    tempCtx.fillStyle = 'red';
                    tempCtx.fillText(currentText, relativeX, relativeY);
                } 
                else if (isAddingArrow && currentArrow) {
                    // 修改箭头绘制部分
                    const startX = (currentArrow.startX - imgX) / scale;
                    const startY = (currentArrow.startY - imgY) / scale;
                    const endX = (currentArrow.endX - imgX) / scale;
                    const endY = (currentArrow.endY - imgY) / scale;
                    
                    // 计算缩放后的箭头头部大小
                    const headLength = 15 / scale;
                    
                    // 绘制箭头
                    const angle = Math.atan2(endY - startY, endX - startX);
                    
                    tempCtx.beginPath();
                    tempCtx.moveTo(startX, startY);
                    tempCtx.lineTo(endX, endY);
                    tempCtx.strokeStyle = 'red';
                    tempCtx.lineWidth = 3 / scale;
                    tempCtx.stroke();
                    
                    tempCtx.beginPath();
                    tempCtx.moveTo(endX, endY);
                    tempCtx.lineTo(
                        endX - headLength * Math.cos(angle - Math.PI / 6),
                        endY - headLength * Math.sin(angle - Math.PI / 6)
                    );
                    tempCtx.lineTo(
                        endX - headLength * Math.cos(angle + Math.PI / 6),
                        endY - headLength * Math.sin(angle + Math.PI / 6)
                    );
                    tempCtx.closePath();
                    tempCtx.fillStyle = 'red';
                    tempCtx.fill();
                }
				else if (isAddingLine && currentLine) {
				    // 计算直线在原始图片上的位置
				    const startX = (currentLine.startX - imgX) / scale;
				    const startY = (currentLine.startY - imgY) / scale;
				    const endX = (currentLine.endX - imgX) / scale;
				    const endY = (currentLine.endY - imgY) / scale;
				    
				    // 绘制直线
				    tempCtx.beginPath();
				    tempCtx.moveTo(startX, startY);
				    tempCtx.lineTo(endX, endY);
				    tempCtx.strokeStyle = currentLine.color || lineColor || 'red';
				    tempCtx.lineWidth = (currentLine.width || lineWidth || 3) / scale;
				    tempCtx.stroke();
				}
                else if (isAddingRect && currentRect) {
                    // 计算矩形在原始图片上的位置和大小
                    const rectX = (currentRect.x - imgX) / scale;
                    const rectY = (currentRect.y - imgY) / scale;
                    const rectWidth = currentRect.width / scale;
                    const rectHeight = currentRect.height / scale;
                    
                    // 绘制矩形
                    tempCtx.beginPath();
                    tempCtx.rect(rectX, rectY, rectWidth, rectHeight);
                    tempCtx.strokeStyle = 'red';
                    tempCtx.lineWidth = 3 / scale;
                    tempCtx.stroke();
                }
                else if (isAddingCircle && currentCircle) {
                    // 计算圆形在原始图片上的位置和大小
                    const circleX = (currentCircle.x - imgX) / scale;
                    const circleY = (currentCircle.y - imgY) / scale;
                    const circleRadius = currentCircle.radius / scale;
                    
                    // 绘制圆形
                    tempCtx.beginPath();
                    tempCtx.arc(circleX, circleY, Math.abs(circleRadius), 0, Math.PI * 2);
                    tempCtx.strokeStyle = 'red';
                    tempCtx.lineWidth = 3 / scale;
                    tempCtx.stroke();
                }
                else if (isAddingDoodle && (doodleStrokes.length > 0 || currentDoodleStroke.length > 0)) {
                    // 如果还有未完成的笔画，先将其添加到已完成的笔画中
                    if (currentDoodleStroke.length > 0) {
                        const strokeToSave = [...currentDoodleStroke];
                        strokeToSave.color = currentDoodleStroke.color;
                        strokeToSave.size = currentDoodleStroke.size;
                        doodleStrokes.push(strokeToSave);
                    }
                    
                    // 计算所有笔画点在原始图片上的位置并绘制
                    doodleStrokes.forEach(stroke => {
                        if (stroke.length > 0) {
                            const scaledStroke = stroke.map(point => ({
                                x: (point.x - imgX) / scale,
                                y: (point.y - imgY) / scale
                            }));
                            
                            tempCtx.beginPath();
                            tempCtx.moveTo(scaledStroke[0].x, scaledStroke[0].y);
                            for (let i = 1; i < scaledStroke.length; i++) {
                                tempCtx.lineTo(scaledStroke[i].x, scaledStroke[i].y);
                            }
                            tempCtx.strokeStyle = stroke.color || brushColor || 'red';
                            tempCtx.lineWidth = (stroke.size || brushSize || 3) / scale;
                            tempCtx.lineCap = 'round';
                            tempCtx.lineJoin = 'round';
                            tempCtx.stroke();
                        }
                    });
                }
                
                img.onload = function() {
                    saveToHistory();
                    currentText = null;
                    currentArrow = null;
                    currentRect = null;
                    currentCircle = null;
					currentLine = null;
                    doodleStrokes = [];
                    currentDoodleStroke = [];
                    isAddingText = false;
                    isAddingArrow = false;
                    isAddingRect = false;
                    isAddingCircle = false;
                    isAddingDoodle = false;
					isAddingLine = false;
                    isEditing = false;
                    arrowSelectedEnd = null;
                    rectSelectedCorner = null;
                    circleSelectedPoint = null;
                    toggleToolbar(false);
                    doodleSettings.style.display = 'none'; // 隐藏涂鸦设置面板
					lineSettings.style.display = 'none';    // 隐藏直线设置面板
                    drawCanvas();
                };
                img.src = tempCanvas.toDataURL('image/png');
            }
        });

        // 删除当前编辑
        deleteBtn.addEventListener('click', () => {
            // 恢复触摸操作
            restoreTouchActions();
            currentText = null;
            currentArrow = null;
            currentRect = null;
            currentCircle = null;
			currentLine = null;
            doodleStrokes = [];
            currentDoodleStroke = [];
            isAddingText = false;
            isAddingArrow = false;
            isAddingRect = false;
            isAddingCircle = false;
            isAddingDoodle = false;
			isAddingLine = false;
            isEditing = false;
            arrowSelectedEnd = null;
            rectSelectedCorner = null;
            circleSelectedPoint = null;
            toggleToolbar(false);
            doodleSettings.style.display = 'none'; // 隐藏涂鸦设置面板
			lineSettings.style.display = 'none'; // 隐藏直线设置面板
            drawCanvas();
        });
		
		// 截图按钮
		document.getElementById('crop-btn').addEventListener('click', startCrop);
		document.getElementById('crop-confirm-btn').addEventListener('click', confirmCrop);
		document.getElementById('crop-cancel-btn').addEventListener('click', cancelCrop);

		// 保存按钮点击事件
		document.getElementById('save-btn').addEventListener('click', function() {
		    // 隐藏其他功能按钮
		    document.getElementById('reset-btn').style.display = 'none';
		    document.getElementById('undo-btn').style.display = 'none';
		    document.getElementById('clear-btn').style.display = 'none';
		    document.getElementById('add-text-btn').style.display = 'none';
		    document.getElementById('add-shape-btn').style.display = 'none';
		    document.getElementById('add-doodle-btn').style.display = 'none';
		    document.getElementById('crop-btn').style.display = 'none';
		    
		    // 显示保存选项按钮
		    document.getElementById('save-view-btn').style.display = 'block';
		    document.getElementById('save-full-btn').style.display = 'block';
			document.getElementById('save-cancel-btn').style.display = 'block';
		    
		    // 隐藏自身
		    this.style.display = 'none';
		});
		
		// 取消保存按钮点击事件
		document.getElementById('save-cancel-btn').addEventListener('click', function() {
		    resetSaveButtons();
		});
		
		// 保存当前视图（用户看到的区域）
		document.getElementById('save-view-btn').addEventListener('click', async function() {
		    try {
		        // 创建与canvas相同尺寸的临时canvas，但使用更高分辨率
		        const tempCanvas = document.createElement('canvas');
		        // 使用2倍尺寸提高清晰度
		        tempCanvas.width = canvas.width * 2;
		        tempCanvas.height = canvas.height * 2;
		        const tempCtx = tempCanvas.getContext('2d');
		        
		        // 设置高质量缩放
		        tempCtx.imageSmoothingEnabled = false;
		        
		        // 计算缩放后的绘制参数
		        const scaleFactor = 2; // 2倍分辨率
		        const imgWidth = img.width * scale * scaleFactor;
		        const imgHeight = img.height * scale * scaleFactor;
		        const imgX = (tempCanvas.width - imgWidth) / 2 + offsetX * scaleFactor;
		        const imgY = (tempCanvas.height - imgHeight) / 2 + offsetY * scaleFactor;
		        
		        // 绘制图片
		        tempCtx.drawImage(img, 0, 0, img.width, img.height, imgX, imgY, imgWidth, imgHeight);
		        
		        // 绘制所有标注（需要按比例放大）
		        if (currentText) {
		            tempCtx.font = `${24 * textScale * scaleFactor}px Arial`;
		            tempCtx.fillStyle = 'red';
		            tempCtx.fillText(currentText, 
		                (textX - offsetX) * scaleFactor + tempCanvas.width/2 - imgWidth/2, 
		                (textY - offsetY) * scaleFactor + tempCanvas.height/2 - imgHeight/2);
		        }
		        
		        // 绘制其他图形元素（箭头、矩形等）也需要类似放大
		        
		        // 转换为高质量JPEG
		        const blob = await new Promise(resolve => {
		            tempCanvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.95); // 提高质量参数
		        });
		        
		        uni.webView.postMessage({
		            action: 'imageSaved',
		            data: {
		                type: 'blob', 
		                blob: await blobToBase64(blob)
		            }
		        });
		        
		        resetSaveButtons();
		    } catch (error) {
		        console.error('保存当前视图出错:', error);
		        resetSaveButtons();
		    }
		});
		
		// 保存完整图片（原始分辨率）
		document.getElementById('save-full-btn').addEventListener('click', async function() {
		    try {
		        // 创建与图片原始尺寸相同的临时canvas
		        const tempCanvas = document.createElement('canvas');
		        tempCanvas.width = img.naturalWidth || img.width;
		        tempCanvas.height = img.naturalHeight || img.height;
		        const tempCtx = tempCanvas.getContext('2d');
		        
		        // 禁用平滑处理以保持清晰度
		        tempCtx.imageSmoothingEnabled = false;
		        
		        // 1. 先绘制原始图片
		        tempCtx.drawImage(img, 0, 0, tempCanvas.width, tempCanvas.height);
		        
		        // 2. 再绘制所有标注（需要按比例缩放）
		        const scaleX = tempCanvas.width / img.width;
		        const scaleY = tempCanvas.height / img.height;
		        
		        // 绘制文字
		        if (currentText) {
		            tempCtx.font = `${24 * textScale * scaleX}px Arial`;
		            tempCtx.fillStyle = 'red';
		            tempCtx.fillText(currentText, textX * scaleX, textY * scaleY);
		        }
		        
		        // 绘制箭头、图形等其他标注（需要类似的比例缩放）
		        // ... 这里添加其他图形元素的绘制代码，都要乘以scaleX/scaleY
		        
		        // 转换为Blob并发送
		        const blob = await new Promise(resolve => {
		            tempCanvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.9);
		        });
		        
		        uni.webView.postMessage({
		            action: 'imageSaved',
		            data: {
		                type: 'blob', 
		                blob: await blobToBase64(blob)
		            }
		        });
				
				resetSaveButtons();
		    } catch (error) {
		        console.error('保存完整图片出错:', error);
				resetSaveButtons();
		    }
		});
		
		// 恢复按钮状态的函数
		function resetSaveButtons() {
		    // 显示常规工具栏按钮
		    document.getElementById('reset-btn').style.display = 'block';
		    document.getElementById('undo-btn').style.display = 'block';
		    document.getElementById('clear-btn').style.display = 'block';
		    document.getElementById('add-text-btn').style.display = 'block';
		    document.getElementById('add-shape-btn').style.display = 'block';
		    document.getElementById('add-doodle-btn').style.display = 'block';
		    document.getElementById('crop-btn').style.display = 'block';
		    document.getElementById('save-btn').style.display = 'block';
		    
		    // 隐藏保存选项按钮
		    document.getElementById('save-view-btn').style.display = 'none';
		    document.getElementById('save-full-btn').style.display = 'none';
			document.getElementById('save-cancel-btn').style.display = 'none';
		}
		
		// Blob转Base64工具函数
		function blobToBase64(blob) {
		    return new Promise((resolve) => {
		        const reader = new FileReader();
		        reader.onload = () => resolve(reader.result.split(',')[1]); // 去掉DataURL前缀
		        reader.readAsDataURL(blob);
		    });
		}

        // 复原按钮
        resetBtn.addEventListener('click', initImage);

        // 回滚按钮
        undoBtn.addEventListener('click', restoreFromHistory);

        // 窗口大小变化
        window.addEventListener('resize', resizeCanvas);

        // 初始化
        initCanvas();
    </script>
</body>
</html>